package com.mofang.powerdekorhelper.activity.login;

import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.activity.MainActivity;
import com.mofang.powerdekorhelper.base.MvpActivity;
import com.mofang.powerdekorhelper.model.ImgCode;
import com.mofang.powerdekorhelper.model.User;
import com.mofang.powerdekorhelper.persenter.LoginPersenter;
import com.mofang.powerdekorhelper.utils.ConnectionUtils;
import com.mofang.powerdekorhelper.utils.LoadPrograss;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.utils.UrlTools;
import com.mofang.powerdekorhelper.view.LoginView;
import com.mofang.powerdekorhelper.witget.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mofang.powerdekorhelper.utils.ImageUtils.base64ToBitmap;

/**
 * Created by luofei on 2016/7/21 0021.
 */

public class LoginActivity extends MvpActivity<LoginView, LoginPersenter> implements LoginView {

    @BindView(R.id.login_title)
    TitleBar mTitleBar;

    //用户名
    @BindView(R.id.login_user_edit)
    EditText mAccount;

    //密码
    @BindView(R.id.login_pwd_edit)
    EditText mPassword;

    //验证码
    @BindView(R.id.login_validate_edit)
    EditText validateEdit;

    //获取验证码
    @BindView(R.id.login_vcode_imv)
    ImageView validateImv;

    @BindView(R.id.login_organized_edit)
    EditText organizedEdit;

    @BindView(R.id.login_department_edit)
    EditText departmentEdit;

    @BindView(R.id.login_validate_continer)
    LinearLayout validateContiner;

    @BindView(R.id.login_username_clear)
    ImageView usernameClear;

    @BindView(R.id.login_password_clear)
    ImageView passwordClear;

    @BindView(R.id.login_organized_clear)
    ImageView organizedClear;

    @BindView(R.id.login_department_clear)
    ImageView departmentClear;

    String userName;
    String password;
    String organizedCode;
    String departmentCode;
    private int tryLoginNum = 0;
    // 验证码的key
    String validatevKey = "";
    // 验证码
    String validate;

    LoadPrograss loadPrograss;

    @Override
    public LoginPersenter initPresenter() {
        return new LoginPersenter();
    }

    @Override
    public void initView() {
        inflateLayout(R.layout.activity_login_layout);
        loadPrograss = new LoadPrograss(this);
        setTextChangedListener();
    }

    @Override
    public void initData() {
        // 透明状态栏
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // 设置沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mTitleBar.setImmersive(true);
        } else {
            mTitleBar.setImmersive(false);
        }
    }

    @OnClick({R.id.login_login_btn, R.id.login_forget_pwd, R.id.login_vcode_imv, R.id.login_username_clear, R.id.login_password_clear,
            R.id.login_organized_clear, R.id.login_department_clear})
    void onclick(View view) {
        switch (view.getId()) {

            case R.id.login_login_btn:

                userName = mAccount.getText().toString();
                password = mPassword.getText().toString();
                validate = validateEdit.getText().toString();
                organizedCode = organizedEdit.getText().toString();
                departmentCode = departmentEdit.getText().toString();

                if (!validateUserInfo(userName, password, organizedCode, departmentCode, validate)) {
                    return;
                }

                // 登录
                presenter.getLoginResult(userName, password, organizedCode, departmentCode, validate, validatevKey);

                break;

            //获取验证码
            case R.id.login_vcode_imv:

                presenter.getValidate();
                break;
            case R.id.login_username_clear:
                mAccount.setText("");
                break;
            case R.id.login_password_clear:
                mPassword.setText("");
                break;
            case R.id.login_organized_clear:
                organizedEdit.setText("");
                break;

            case R.id.login_department_clear:
                departmentEdit.setText("");
                break;

            case R.id.login_forget_pwd:

                // 忘记密码
                toActivity(this, ForgetPasswordActivity.class);
                break;
        }
    }

    // 登录
    @Override
    public void setLoginResult(User user) {
        if (user != null) {
            if (user.getCode().equals("0")) {
                // 登录成功
                toTargetActivity(user);
                ConnectionUtils connectionUtils = ConnectionUtils.getInstance();
                connectionUtils.init(LoginActivity.this, UrlTools.WSUrl + user.getResult().getId());
                connectionUtils.connect();
            } else {
                T.showShort(this, user.getMessage());
                tryLoginNum++;
                if (tryLoginNum >= 4) {
                    // 登陆失败3次后显示验证码
                    validateContiner.setVisibility(View.VISIBLE);
                    presenter.getValidate();
                }
            }

        } else {
            T.showShort(this, "登陆失败" + user.getMessage());
        }
    }


    // 保存数据
    private void toTargetActivity(User user) {

        SharePerforenceUtils sp = SharePerforenceUtils.getInstance(this);
        sp.setLogin(true);
        sp.setUserID(user.getResult().getId());
        sp.setUserName(user.getResult().getUser_name());
        sp.setName(user.getResult().getName());
        sp.setPhone(user.getResult().getPhone());
        sp.setBelongCompany(user.getResult().getFiliale());
        sp.setShopId(user.getResult().getShop_id());
        sp.setNodeId(user.getResult().getNode3());

        toActivity(LoginActivity.this, MainActivity.class);

        finish();
    }

    // 图片验证码
    @Override
    public void setImageCode(ImgCode baseImg) {

        String baseImgStr = baseImg.getResult().getImageStr();

        validateImv.setImageBitmap(base64ToBitmap(baseImgStr));

        validatevKey = baseImg.getResult().getVkey();
    }

    /**
     * 非空验证
     *
     * @param account
     * @param pwd
     * @return
     */
    private boolean validateUserInfo(String account, String pwd, String organizedCode, String departmentCode, String validate) {

        if (TextUtils.isEmpty(organizedCode)) {

            T.showShort(this, "请输入组织代码");
            return false;
        }

        if (TextUtils.isEmpty(departmentCode)) {

            T.showShort(this, "请输入部门编号");
            return false;
        }

        if (TextUtils.isEmpty(account)) {

            T.showShort(this, getString(R.string.account_notbe_null));
            return false;
        }

        if (TextUtils.isEmpty(pwd)) {

            T.showShort(this, getString(R.string.pwd_notbe_null));
            return false;
        }


        if (pwd.length() < 6) {
            T.showShort(this, getString(R.string.pwd_format_error));
            return false;
        }

        if (tryLoginNum >= 4) {
            if (validate != null) {
                if (TextUtils.isEmpty(validate)) {
                    T.showShort(this, getString(R.string.vcode_notbe_null));
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public void setTextChangedListener() {

        mAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    usernameClear.setVisibility(View.VISIBLE);
                } else {
                    usernameClear.setVisibility(View.GONE);
                }

            }
        });

        mPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    passwordClear.setVisibility(View.VISIBLE);
                } else {
                    passwordClear.setVisibility(View.GONE);
                }
            }
        });

        organizedEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    organizedClear.setVisibility(View.VISIBLE);
                } else {
                    organizedClear.setVisibility(View.GONE);
                }
            }
        });

        departmentEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    departmentClear.setVisibility(View.VISIBLE);
                } else {
                    departmentClear.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void showProgress() {
        loadPrograss.show();
    }

    @Override
    public void hideProgress() {
        loadPrograss.hide();
    }

    @Override
    public void toast(CharSequence s) {

        T.showShort(this, s);
    }

    @Override
    public void toast(int id) {
        T.showShort(this, getResources().getString(id));
    }

    @Override
    public void showNullLayout() {

    }

    @Override
    public void hideNullLayout() {

    }

    @Override
    public void showErrorLayout(View.OnClickListener listener) {

    }

    @Override
    public void hideErrorLayout() {

    }

    @Override
    public void onError(String errorInfo) {
        toast(errorInfo);
    }
}
